package view;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.Blog;
import dao.BlogDao;
import dao.User;
import dao.UserDao;
import session.Session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = Session.isLogin(req);
        if (user == null){
            //resp.sendRedirect("login.html");
            resp.setStatus(403);
            String html = "<h3> 请先登录 </h3>";
            resp.getWriter().write(html);
            return;
        }
        resp.setContentType("application/json;charset=utf-8");
        String blogId = req.getParameter("blogId");
        BlogDao blogDao = new BlogDao();
        try {
            Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
            if (user.getUserId() == blog.getUserId()){
                user.setIsSelf(1);
            }else {
                user.setIsSelf(0);
            }
            String jsonString = objectMapper.writeValueAsString(user);
            resp.getWriter().write(jsonString);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
